package com.material.common.wx.base;

import com.material.common.wx.base.response.BaseResponse;
import com.material.common.wx.consts.ApiUrl;
import com.material.common.wx.product.response.ProductListResponse;
import com.wechat.pay.java.core.http.HttpClient;
import com.wechat.pay.java.core.http.HttpHeaders;
import com.wechat.pay.java.core.http.HttpMethod;
import com.wechat.pay.java.core.http.HttpRequest;
import com.wechat.pay.java.core.http.HttpResponse;
import com.wechat.pay.java.core.http.MediaType;
import com.wechat.pay.java.core.http.RequestBody;
import com.wechat.pay.java.core.util.GsonUtil;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ganxinge
 */
public class BaseService {

    private final HttpClient httpClient;

    public BaseService(HttpClient httpClient) {
        this.httpClient = httpClient;
    }

    public BaseResponse getAccessToken(String appId,String appSecret){
        Map<String,String> params = new HashMap<>(16);
        params.put("appId",appId);
        params.put("secret",appSecret);
        RequestBody requestBody = (new com.wechat.pay.java.core.http.JsonRequestBody.Builder()).body(GsonUtil.toJson(params)).build();
        String requestPath = ApiUrl.ACCESS_TOKE;
        String url = MessageFormat.format(requestPath,appId,appSecret);
        HttpHeaders headers = new HttpHeaders();
        headers.addHeader("Accept", MediaType.APPLICATION_JSON.getValue());
        headers.addHeader("Content-Type", MediaType.APPLICATION_JSON.getValue());
        HttpRequest httpRequest = (new com.wechat.pay.java.core.http.HttpRequest.Builder()).httpMethod(HttpMethod.POST).url(requestPath).headers(headers).body(requestBody).build();
        HttpResponse<BaseResponse> httpResponse = this.httpClient.execute(httpRequest, BaseResponse.class);
        BaseResponse serviceResponse = httpResponse.getServiceResponse();
        return serviceResponse;
    }
}
